<template>
  <div>
    <Select
      v-bind="$attrs"
      v-model:value="value"
      style="width: 100%"
      :options="data.map((item) => ({ value: item.id, label: item.name }))"
      :placeholder="placeholder"
      :mode="mode"
    >
      <template #dropdownRender="{ menuNode: menu }" v-if="isShowAdd">
        <component :is="menu" />
        <Divider style="margin: 4px 0" />
        <div
          style="padding: 4px 8px; cursor: pointer"
          @mousedown="(e) => e.preventDefault()"
          @click="add"
        >
          <plus-outlined />
          {{ t('新增') }}
        </div>
      </template>
    </Select>
    <DicDetailDrawer @register="registerDetailDrawer" @success="handleDetailSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Select, Divider } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { onMounted, ref, unref, watch } from 'vue';
  import { getDicDetailList } from '/@/api/system/dic';
  import { DicDetailListParams } from '/@/api/system/dic/model';
  import DicDetailDrawer from '../components/DicDetailDrawer.vue';
  import { useDrawer } from '../../Drawer/src/useDrawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['change']);

  const props = defineProps({
    value: [String, Array],
    itemId: {
      type: String,
      required: true,
    },
    placeholder: String,
    isShowAdd: {
      type: Boolean,
      default: true,
    },
    mode: {
      type: String,
    },
    isDefaultValue: {
      type: Boolean,
      default: false,
    },
  });

  const value = ref();

  const data = ref<Recordable[]>([]);

  onMounted(() => {
    fetch();
  });

  watch(
    () => value,
    (val) => {
      emit(
        'change',
        unref(value),
        unref(data).find((x) => x.id === val),
      );
    },
    { deep: true },
  );

  watch(
    () => props.value,
    (val) => {
      value.value = val;
      emit(
        'change',
        unref(value),
        unref(data).find((x) => x.id === val),
      );
    },
    { deep: true },
  );

  async function fetch() {
    const params = { itemId: props.itemId } as DicDetailListParams;
    data.value = ((await getDicDetailList(params)) as unknown as Recordable[]) || [];

    value.value = props.value || (props.isDefaultValue ? data.value[0].id : undefined);
  }

  const [registerDetailDrawer, { openDrawer }] = useDrawer();

  const add = () => {
    openDrawer(true, { itemId: props.itemId });
  };

  const handleDetailSuccess = () => {
    fetch();
  };
</script>
